package com.lxb.store.controller;

import com.lxb.store.entity.Role;
import com.lxb.store.entity.User;
import com.lxb.store.service.RoleService;
import com.lxb.store.service.UserService;
import net.bytebuddy.build.ToStringPlugin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.persistence.ManyToOne;
import java.util.HashMap;
import java.util.Map;

@Controller
public class RegisterController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;


    @GetMapping("/register")
    public String registerIndex(){

        return "register";


    }

    @PostMapping("/register")
    @ResponseBody
    public Map<String,String> register(User user){

        Map<String,String> ret = new HashMap();

        if(user == null){
            ret.put("status","error");
            ret.put("msg","请联系开发人员");
            return  ret;
        }
        if("".equals(user.getUsername().trim())){
            ret.put("status","error");
            ret.put("msg","用户名不能为空");
            return  ret;
        }
        if("".equals(user.getEmail().trim())){
            ret.put("status","error");
            ret.put("msg","邮箱不能为空");
            return  ret;
        }
        if("".equals(user.getPassword().trim())){
            ret.put("status","error");
            ret.put("msg","密码不能为空");
            return  ret;
        }

        //判断用户名是否存在
        User existUser = userService.getByUsername(user.getUsername());
        if(existUser != null){
            ret.put("status","error");
            ret.put("msg","该用户名已存在");
            return  ret;
        }

        Role role = new Role();
        role.setName("用户");

        user.setRole(role); // 保存角色到用户里面

        User addUser = userService.add(user);
        if(addUser == null){
            ret.put("status","error");
            ret.put("msg","注册失败");
            return  ret;
        }

        ret.put("status","success");
        ret.put("msg","注册成功");
        return  ret;
    }
}
